import os
from django.shortcuts import render
from django.http import JsonResponse
from mychat import settings
from rest_framework.views import APIView

from rest_framework.response import Response

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import json
from langchain_community.document_loaders import TextLoader

from langchain.embeddings import CacheBackedEmbeddings
from langchain.storage import LocalFileStore
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain.embeddings.dashscope import DashScopeEmbeddings

from langchain_text_splitters import CharacterTextSplitter

import json


class TxtUpload(APIView):
    def post(self,request):
        file = request.FILES['file']
         
        # 生成文件路径  
        file_path = os.path.join(settings.MEDIA_ROOT, file.name)  
        with open(file_path, 'wb+') as destination:  
            for chunk in file.chunks():  
                destination.write(chunk) 
        
        
        
                
        return Response({"code":200}) 
    
    # def getinfo(file_path):
    #     with open(file_path, 'r') as file: 
            # content = file.read()
            # content.split('\n\n')
            # prompt = ""
            # llm = Tongyi()
            # ret = llm.invoke(prompt)
            
            # json.load(ret)
            
            # # 存数据库
            


# Create your views here.
class UsersView(APIView):
    def post(self,request):
        name = request.data['name']
        age = request.data['age']
       
        return JsonResponse({"code":200})
        
    def get(self,request):
        file_path = os.path.join(settings.BASE_DIR, 'demo','NBA新闻.txt')
        # 加载并分割文档
        loader = TextLoader(file_path, encoding='utf-8')
        dosc = loader.load()
        print(dosc)
        return Response({"code": 200, 'message': "成功"})
    
class FileUpload(APIView):
    def post(self,request):
        file = request.FILES['file']
         
        # 生成文件路径  
        file_path = os.path.join(settings.MEDIA_ROOT, file.name)  
        with open(file_path, 'wb+') as destination:  
            for chunk in file.chunks():  
                destination.write(chunk) 
                
        return Response({"code":200})  

db = None

def add_faiss(filepath):
    global db
    # 实例化向量嵌入器
    embeddings = DashScopeEmbeddings()
    # 初始化缓存存储器
    store = LocalFileStore("./cache/")
    # 创建缓存支持的嵌入器
    cached_embedder = CacheBackedEmbeddings.from_bytes_store( embeddings, store, namespace=embeddings.model)
    
    # 加载文档并将其拆分成片段
    doc = TextLoader(filepath,encoding='utf-8').load()
    spliter = CharacterTextSplitter("\n",chunk_size=200, chunk_overlap=0)
    chunks = spliter.split_documents(doc)
    # 创建向量存储
    db = FAISS.from_documents(chunks, cached_embedder)